#include <coreai/vision/textrecognition.h>
#include <gio/gio.h>
#include <gio/giotypes.h>

#include <iostream>
#include <thread>

const char *TEST_FILE_PATH = "/home/zkx/Pictures/test.png";

void callback(TextRecognitionResult *result, void *user_data) {
    fprintf(stdout, "Start printing results.\n");

    int textLineNum = 0, pointsNum = 0;
    fprintf(stdout, "text        : %s\n",
            text_recognition_result_get_value(result));
    fprintf(stdout, "err code    : %i\n",
            text_recognition_result_get_error_code(result));
    fprintf(stdout, "err message : %s\n",
            text_recognition_result_get_error_message(result));

    _TextLine **textline =
        text_recognition_result_get_text_lines(result, &textLineNum);
    if (textline == nullptr) {
        fprintf(stderr, "The result is invalid, please check image\n");
        return;
    }

    for (int i = 0; i < textLineNum; ++i) {
        PixelPoint *point =
            text_line_get_corner_points(textline[i], &pointsNum);
        if (point == nullptr) {
            fprintf(stderr, "No point\n");
            return;
        }
        fprintf(stdout, "The %i line text: %s\n", i,
                text_line_get_value(textline[i]));

        for (int i = 0; i < pointsNum; i++) {
            printf("The corner points text %d: (%d, %d)\n", i, point[i].x,
                   point[i].y);
        }
    }

    if (user_data != nullptr) {
        const char *userData = static_cast<const char *>(user_data);
        fprintf(stdout, "%s\n", userData);
    } else {
        fprintf(stdout, "user data is nullptr\n");
    }

    fprintf(stdout, "Printing result completed.\n");
}

void test01_OcrFromFile() {
    const char *userData = "Test genai vision from image file\n";

    TextRecognitionSession *session = text_recognition_create_session();

    TextRecognitionModelConfig *config = text_recognition_model_config_create();
    text_recognition_model_config_set_name(config, "vision");
    text_recognition_model_config_set_deploy_type(config,
                                                  ModelDeployType::OnDevice);

    text_recognition_set_model_config(session, config);

    text_recognition_init_session(session);

    text_recognition_result_set_callback(session, callback, (void *)userData);

    text_recognition_recognize_text_from_image_file_async(session,
                                                          TEST_FILE_PATH);

    GMainLoop *pMainLoop = g_main_loop_new(nullptr, false);

    std::thread ctrlThread([&session, &config, pMainLoop] {
        while (std::getchar() != '\n') {
        }
        text_recognition_destroy_session(&session);
        text_recognition_model_config_destroy(&config);
        g_main_loop_quit(pMainLoop);
    });

    ctrlThread.detach();
    g_main_loop_run(pMainLoop);
    g_main_loop_unref(pMainLoop);
}

int main() {
//    test01_OcrFromFile();

    return 0;
}
